package ar.edu.itba.it.pdc.httpParser;

import ar.edu.itba.it.pdc.httpParser.exceptions.HttpBadRequestException;
import ar.edu.itba.it.pdc.httpParser.models.HttpBody;
import ar.edu.itba.it.pdc.httpParser.models.HttpRequest;
import ar.edu.itba.it.pdc.httpParser.models.HttpRequestLine;
import ar.edu.itba.it.pdc.httpParser.models.HttpResponse;
import ar.edu.itba.it.pdc.httpParser.models.HttpStatusLine;

public class HttpResponseParser extends HttpParser{

	HttpRequest req;
	
	public HttpResponseParser(Lexer lexer, HttpRequest request) {
		this.lexer = lexer;
		it = new StatusLineParser();
		model = new HttpResponse();
		req = request;
	}
	
	public int setBodyParser() throws HttpBadRequestException {
		if (((HttpRequestLine)req.getInitialLine()).getMethod().toString().equals("HEAD")
				|| ((HttpStatusLine) it.getModel()).getStatusCode() == 204
				|| ((HttpStatusLine) it.getModel()).getStatusCode() == 304
				|| (((HttpStatusLine) it.getModel()).getStatusCode() > 100 
				&& ((HttpStatusLine) it.getModel()).getStatusCode() < 200)) {
			
			state = State.END;
			bp = new NoBoadyParser();
			model.setBody((HttpBody)bp.getModel());
			if (connectionClose) {
				return -1;
			} else {
				return 0;
			}

		} else if (model.getHeaderValue("Transfer-Encoding") != null
				&& "chunked".equals(model.getHeaderValue("Transfer-Encoding")
						.toLowerCase())) {

			state = State.BODY;
			bp = new ChunkedBodyParser();
		} else if (model.getHeaderValue("Content-Length") != null) {
			state = State.BODY;
			int bytesToRead = Integer.parseInt(model.getHeaderValue("Content-Length"));
			bp = new LengthBodyParser(bytesToRead);

			if (!connectionClose && bytesToRead <= 0) {
				model.setBody((HttpBody)bp.getModel());
				state = State.END;
				return 0;
			}
			return bytesToRead;
		} else {
			// TODO handle multipart

			state = State.BODY;
			bp = new ConnectionCloseBodyParser();
		}
		
		return -1;
	}
}
